<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app"></div>
    <template id="t1">
      <div>
        <p>
          用户名
          <input @input="valid('username',$event)" type="text" />
          <span v-if="error.username===false">用户名必须2到18个字符</span>
        </p>
        <p>
          手机
          <input @input="valid('phone',$event)" type="text" />
          <span v-if="error.phone===false">手机格式错误</span>
        </p>
      </div>
    </template>
    <script src="./vue.js"></script>
    <script>
      // 数据驱动视图
      const vm = new Vue({
        el: "#app",
        template: "#t1",
        data: {
          error: {
            username: true,
            phone: true,
          },
        },
        methods: {
          valid(name, e) {
            const value = e.target.value;
            if (name === "username") {
              this.error.username = /^[a-z]{2,18}$/.test(value);
            }
            if (name === "phone") {
              this.error.phone = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value);
            }
          },
        },
      });
    </script>
  </body>
</html>
